package io.renren.modules.receiveJobDemo.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.receiveJobDemo.dto.TaskAssignmentDTO;
import io.renren.modules.receiveJobDemo.entity.UserEntity;
import io.renren.modules.receiveJobDemo.excel.TaskAssignmentExcel;
import io.renren.modules.receiveJobDemo.service.TaskAssignmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 任务分配表
 *
 * @author Musk.gqh 1259757804@qq.com
 * @since 1.0.0 2024-05-20
 */
@RestController
@RequestMapping("receiveJobDemo/taskassignment")
@Api(tags="任务分配表")
public class TaskAssignmentController {
    @Autowired
    private TaskAssignmentService taskAssignmentService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("receiveJobDemo:taskassignment:page")
    public Result<PageData<TaskAssignmentDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        String loginUserType =  (String)params.get("loginUserType");
        String loginUsername = (String) params.get("loginUsername");
        PageData<TaskAssignmentDTO> page = taskAssignmentService.page(params);
        for (TaskAssignmentDTO taskAssignmentDTO : page.getList()) {
            if(taskAssignmentDTO.getFlag() == 1){
                taskAssignmentDTO.setResult("打单中");
            }else if(taskAssignmentDTO.getFlag() == 2){
                taskAssignmentDTO.setResult("已打完");
            }else{
                taskAssignmentDTO.setResult("未开打");
            }
        }
        if(!Objects.equals(loginUserType, "管理员") && !Objects.equals(loginUsername, "admin")){
            List<TaskAssignmentDTO> taskList = new ArrayList<>();
            for (TaskAssignmentDTO taskAssignmentDTO : page.getList()) {
                if(Objects.equals(taskAssignmentDTO.getAssign(), loginUsername)){
                    taskList.add(taskAssignmentDTO);
                }
            }
            page.setList(taskList);
        }
        return new Result<PageData<TaskAssignmentDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("receiveJobDemo:taskassignment:info")
    public Result<TaskAssignmentDTO> get(@PathVariable("id") Long id){
        TaskAssignmentDTO data = taskAssignmentService.get(id);

        return new Result<TaskAssignmentDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("receiveJobDemo:taskassignment:save")
    public Result save(@RequestBody TaskAssignmentDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setFlag(0);//默认未开打

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = sdf.format(date);

        dto.setCreateTime(currentDateTime);
        dto.setUpdateTime(currentDateTime);
        taskAssignmentService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("receiveJobDemo:taskassignment:update")
    public Result update(@RequestBody TaskAssignmentDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = sdf.format(date);

        dto.setUpdateTime(currentDateTime);
        taskAssignmentService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("receiveJobDemo:taskassignment:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        taskAssignmentService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("receiveJobDemo:taskassignment:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<TaskAssignmentDTO> list = taskAssignmentService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "任务分配表", list, TaskAssignmentExcel.class);
    }

    //查询所有用户名
    @GetMapping("queryUser")
    public Result queryUser(){
        List<UserEntity> list = taskAssignmentService.queryUsername();
        System.out.println(list);
        return new Result().ok(list);
    }

    @GetMapping("taskStart/{id}")
    public Result taskStart(@PathVariable("id") Integer id){
        taskAssignmentService.updateStartById(id);
        return new Result();
    }

    @GetMapping("taskEnd/{id}")
    public Result taskEnd(@PathVariable("id") Integer id){
        taskAssignmentService.updateEndById(id);
        return new Result();
    }

    /**
    * @Description: 根据token查role_name
    * @Author: gqh
    * @Date: 2024/5/30 10:55
    */
    @GetMapping("queryRoleNameIdByToken/{token}")
    public Result queryUserIdByToken(@PathVariable("token") String token){
        String roleName = taskAssignmentService.queryRoleNameIdByToken(token);
        return new Result().ok(roleName);
    }

    /**
    * @Description: 根据token查username
    * @Author: gqh
    * @Date: 2024/5/30 11:25
    */
    @GetMapping("queryUsernameByToken/{token}")
    public Result queryUsernameByToken(@PathVariable("token") String token){
        String username = taskAssignmentService.queryUsernameByToken(token);
        return new Result().ok(username);
    }


}